<?php
/**
 *
 * @author Strawberry🍓
 * @date 2021-05-21 4:08 下午
 *
 */

namespace app\common\model\tang;


use app\admin\model\AdminUser;
use app\admin\model\GroupAccess;
use app\common\impl\Comm;
use app\common\model\CommonBaseModel;
use app\common\model\tang\Cost;
use \PhpOffice\PhpSpreadsheet\IOFactory;
use \PhpOffice\PhpSpreadsheet\Spreadsheet;
use app\common\model\tang\Merchant;


class OwnerOperate extends CommonBaseModel implements Comm
{

    /**
     * 商户追缴欠费统计
     */

    public function getAdminReportData($param = [], $order = 'id asc', $where = [], $nickname = '')
    {

        $adminInfo = session(ADMIN_LOGIN_INFO);
        if($adminInfo['id']!=1){
            //查找负责的商户信息
            $group = (new GroupAccess())->where('uid',$adminInfo['id'])->value('group_id');
            if($group!=7){
            $merchanids = (new Principal())->where('principal_id',$adminInfo['id'])->find();
            if($merchanids){//说明是主负责人
                $where[] = ['principal_id','=',$adminInfo['id']];
            }else{
                $where[] = ['principal_id','in',[0]];
            }}

        }

        $model = new Principal();
        if(!empty($param['section_id'])&&isset($param['section_id'])){
            $where[] = ['section_id','in',$param['section_id']];
        }
        if(!empty($param['principal_id'])&&isset($param['principal_id'])){
            $where[] = ['principal_id','=',$param['principal_id']];
        }
//        if(empty($param['startDate'])){
//            $start['start_time'] = date('Y-m-01');
//            $start['end_time'] = date('Y-m-t');
//        }else{
//            $tmp = explode('~',$param['startDate']);
//            $start['start_time'] = $tmp[0].'-01';
//            $start['end_time'] = $tmp[1].'-01';
//        }
        if(empty($param['startDate'])){
            if(!empty($param['time_type'])){
                if($param['time_type']==1){ //当前月
                    $start['start_time'] = date('Y-m-01');
                    $start['end_time'] = date('Y-m-t');
                }else if($param['time_type']==2){
                    $M = date('m');
                    if($M=='01'||$M=='02'||$M=='03'){
                        $start['start_time'] = date('Y').'-01-01';
                        $start['end_time'] = date('Y-03-t');
                    }else if ($M=='04'||$M=='05'||$M=='06'){
                        $start['start_time'] = date('Y').'-03-01';
                        $start['end_time'] = date('Y-06-t');
                    }else if ($M=='07'||$M=='08'||$M=='09'){
                        $start['start_time'] = date('Y').'-07-01';
                        $start['end_time'] = date('Y-09-t');
                    }else{
                        $start['start_time'] = date('Y').'-10-01';
                        $start['end_time'] = date('Y-12-t');
                    }
//                    dd(date('m',strtotime('2023-01')));
//                    $start['start_time'] = date('m');
//                    $start['end_time'] = date('Y-m-t');
                }else if($param['time_type']==3){
                    $start['start_time'] = date('Y').'-01-01';
                    $start['end_time'] = date('Y').'-12-31';
                }
            }else{
                $start['start_time'] = date('Y-m-01');
                $start['end_time'] = date('Y-m-t');
            }

        }else{
            if(strpos($param['startDate'],'~')!==false ){
                $tmp = explode('~',$param['startDate']);
                $start['start_time'] = $tmp[0].'-01';
                $start['end_time'] = $tmp[1].'-01';

            }else if(strpos($param['startDate'],'-')!==false){
                $start['start_time'] = $param['startDate'].'-01-01';
                $start['end_time'] = date($param['startDate'].'-t',strtotime($param['startDate']));
            }else{
                $start['start_time'] = $param['startDate'].'-01-01';
                $start['end_time'] = $param['startDate'].'-12-31';
            }
        }

        if (isset($param['export']) && $param['export']) {
            $this->export( session('OwnerOperate'),session('operate_time'));
        } else {
            $data = $model->with(['adminUser'])->where($where)->order($order)->select()->toArray();
        }
        $datas = $this->getList($data,$start);

        $count = count($datas);
        //page??总页数
        $page = $param['page'];
        $limit = $param['limit'];
        $datas = array_splice($datas, ($page - 1) * $limit, $limit);
        return parent::ajaxResult($datas, $count);
    }

    public function getList($data,$start)
    {
        session('operate_time',$start);
        $costModel = new Cost();
        $datas = [];
        if ($data) {
            foreach ($data as $kk=>$row){

                $datas[$kk]['XH'] = $kk+1;
                $costAll = 0;
                $pay_cost = 0;
                $explodeG = explode(',',$row['principal']);
                $explodeM = explode(',',$row['merchant_ids']);
                $costAll = $costModel->whereIn('merchant_id',$explodeM)->where('start_time','>=',strtotime($start['start_time']))->where('end_time','<=',strtotime($start['end_time']))->sum('all_amount');
                $pay_cost = $costModel->whereIn('merchant_id',$explodeM)->where('start_time','>=',strtotime($start['start_time']))->where('end_time','<=',strtotime($start['end_time']))->sum('pay_amount');
                $datas[$kk]['name'] = $row['name'];
                if($row['section_id']==1)$datas[$kk]['section_name'] = '营运一部';
                if($row['section_id']==2)$datas[$kk]['section_name'] = '营运二部';
                if($row['section_id']==3)$datas[$kk]['section_name'] = '营运三部';
                if($row['section_id']==4)$datas[$kk]['section_name'] = '分期';
                if($row['section_id']==5)$datas[$kk]['section_name'] = '诉讼';
                $datas[$kk]['merchant_sum'] = $row['merchant_sum'];
                $datas[$kk]['costAll'] = $costAll/100;
                $datas[$kk]['pay_cost'] = $pay_cost/100;
                $owner_cost = bcsub($costAll,$pay_cost,2);
                $datas[$kk]['owner_cost'] =$owner_cost/100;
                if($costAll>0){
                    $datas[$kk]['SJL'] = bcmul(bcdiv(bcsub($costAll,$owner_cost,2),$costAll,2),100).'%';
                }else{
                    $datas[$kk]['SJL'] = '100%';
                }
            }

        }
        session('OwnerOperate',$datas);
        return $datas;
    }

    private static $cellKey = array(
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'
    );

    public function export($data, $starttime)
    {
        $name = '营运追缴欠费统计';
        $head = ['序号', '分组负责人', '分组名称', '管理商户', '欠费(元)', '应收(元)', '实收(元)', '收缴率(%)'];
        $styleArray = [
            'alignment' => [
                'horizontal' => 'center', //水平居中
                'vertical' => 'center', //垂直居中
            ],
            'font' => [
//                'name' => '黑体',
                'bold' => false,
//                'size' => 10
            ]];
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet()->setTitle('营运追缴欠费统计');
        //第一行
        $sheet->mergeCells('A1:H1', '');
        $spreadsheet->setActiveSheetIndex(0)->setCellValue('A1', '营运追缴欠费统计');

        $spreadsheet->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
        $spreadsheet->getActiveSheet()->getStyle('A1')->getFont()->setSize(20);
        $spreadsheet->getActiveSheet()->getRowDimension(1)->setRowHeight(30);
        $sheet->getStyle(1)->applyFromArray($styleArray);
        //第二行
        $sheet->mergeCells('A2:H2', '');
        $spreadsheet->setActiveSheetIndex(0)->setCellValue('A2', '日期:' . $starttime['start_time'].'~'.$starttime['end_time']);//设置行内值
        $spreadsheet->getActiveSheet()->getRowDimension(2)->setRowHeight(30);
        $spreadsheet->getActiveSheet()->getStyle('A2')->getFont()->setBold(true);//是否加粗
        $spreadsheet->getActiveSheet()->getStyle('A2')->getFont()->setSize(15);//设置字体大小
        $sheet->getStyle(2)->applyFromArray($styleArray);
        $sheet->mergeCells('A3:H3', '');
        $spreadsheet->setActiveSheetIndex(0)->setCellValue('A3', '总应缴:'.session('all_data_operate')['all_money'].'元 总实缴:'.session('all_data_operate')['all_shi'].'元总欠款:'.session('all_data_operate')['all_qian'].'元 总缴纳率:'.session('all_data_operate')['all_jiaona']);//设置行内值
        $spreadsheet->getActiveSheet()->getRowDimension(2)->setRowHeight(30);
        $spreadsheet->getActiveSheet()->getStyle('A3')->getFont()->setBold(true);//是否加粗
        $spreadsheet->getActiveSheet()->getStyle('A3')->getFont()->setSize(15);//设置字体大小
        $sheet->getStyle(2)->applyFromArray($styleArray);
        //第三行
        for ($i = 0; $i < count($head); $i++) {
            $spreadsheet->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//设置水平居中
            $spreadsheet->getActiveSheet()->getColumnDimension(self::$cellKey[$i])->setWidth(13);
            $sheet->setCellValue(self::$cellKey[$i] . '4', $head[$i]);
            $spreadsheet->getActiveSheet()->getStyle(self::$cellKey[$i] . '4')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);//设置垂直居中
        }
        /*--------------开始从数据库提取信息插入Excel表中------------------*/
        $row =5;
        foreach ($data as $order){
            $clo = 1;
            foreach ($order as $val){
                $sheet->getStyle($row)->applyFromArray($styleArray);
                $spreadsheet->getActiveSheet()->getRowDimension($row)->setRowHeight(30);
                $spreadsheet->setActiveSheetIndex(0)->setCellValueByColumnAndRow($clo,$row,$val);
                $clo++;
            }
            $row++;
        }
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name . '.xlsx"');
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($spreadsheet, 'Xlsx');

        $objWriter->save('php://output');
        //删除清空：
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        exit;
    }


    public function delById($id)
    {
        // TODO: Implement delById() method.
    }

    public function doAll($data)
    {
        // TODO: Implement doAll() method.
        return parent::doAllData($data);
    }

    public function getAdminPageData($param = [], $order = 'id asc', $where = [], $nickname = '')
    {
    }
}